import enums from '@/utils/enum'

/**
 * 弹窗表单组合式函数
 * 
 * @param {Object} formRef 表单 ref，必填
 * @param {String} moduleName 模块名称，必填
 * @param {Object} defaultFormData 默认表单数据
 * @param {Function} beforeOpenFn 打开弹窗之前回调
 * @param {Function} addApi 新增保存接口
 * @param {Function} updateApi 修改保存接口
 */
export const useFormDialog = (
  formRef,
  moduleName = '',
  defaultFormData = {},
  beforeOpenFn,
  addApi,
  updateApi
) => {
  const state = reactive({
    form: {},
    title: '',
    visible: false,
    type: '',
    loading: false
  })
  
  const { formType } = enums
  
  const { proxy } = getCurrentInstance()
  
  const closeDialog = () => {
    state.visible = false
    // resetForm()
  }
  
  /**
   * 表单重置
   */
  const resetForm = () => {
    state.form = JSON.parse(JSON.stringify(defaultFormData))
    formRef?.value?.resetFields()
  }
  
  /**
   * 打开弹窗
   * 
   * @param {String} type 弹窗类型（add、edit、view）
   * @param {Object} row 行数据
   */
  const openDialog = async (type, row) => {
    state.type = type
    resetForm()
    if (beforeOpenFn) {
      proxy.$modal.loading('加载中...')
      await beforeOpenFn(type, row).finally(() => {proxy.$modal.closeLoading()})
    }
    state.loading = false
    state.visible = true
    state.title = `${formType[type]?.title || ''}${moduleName}`
  }
  
  const _submitForm = async (submitOkFn) => {
    const type = state.form.id != null ? 'edit' : 'add'
    const api = type === 'edit' ? updateApi : addApi
    state.loading = true
    api(state.form).then(res => {
      if (!res.msg) proxy.$modal.msgSuccess(`${formType[type].title}${moduleName}成功`)
      state.visible = false
      submitOkFn?.(res, type)
    }).finally(() => {
      state.loading = false
    })
  }
  
  /**
   * 表单提交
   * 
   * @param {Function} submitOkFn 提交成功回调
   */
  const submitForm = async (submitOkFn) => {
    if (formRef != null) {
      formRef.value.validate(async valid => {
        if (valid) {
          await _submitForm(submitOkFn)
        } else {
          proxy.$modal.msgWarning('数据校验不通过，请核实!')
        }
      })
    } else {
      await _submitForm(submitOkFn)
    }
  }
  
  /**
   * 表单提交，用于非新增/编辑
   * 
   * @param {Function} saveApi 保存接口
   * @param {String} successTxt 操作成功提示信息
   * @param {Function} submitOkFn 提交成功回调
   */
  const submitDialog = async (saveApi, successTxt, submitOkFn) => {
    formRef.value.validate(valid => {
      if (valid) {
        state.loading = true
        saveApi(state.form).then(res => {
          if (!res.msg) proxy.$modal.msgSuccess(successTxt)
          state.visible = false
          submitOkFn?.(res)
        }).finally(() => {
          state.loading = false
        })
      } else {
        proxy.$modal.msgWarning('数据校验不通过，请核实!')
      }
    })
  }

  return {
    ...toRefs(state),
    openDialog,
    closeDialog,
    submitForm,
    submitDialog
  }
}